package com.xmg.hot.sougou;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xmg.hot.common.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xmg
 * @date 2024/6/2 16:19
 */
public class HotSouGou {
    public static void main(String[] args) {
        String apiKey = "xxx";
        String secretKey = "xxxxx";
        String host = "http://api.dataguan.com/";
//        String host = "http://localhost:8082/";
        String path = "api/center/getWangYiHot";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        String sign = createSign(apiKey,secretKey);
        bodys.put("apiKey", apiKey);
        bodys.put("sign", sign);
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.getEntity());
            //获取response的body
            JSONObject jsStr = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            System.out.println(jsStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建签名
     * @return
     */
    public static String createSign(String apiKey,String apiSecret){
        Map<String,String> map = new HashMap<String, String>();
        map.put("apiKey",apiKey);
        map.put("apiSecret",apiSecret);
        String jsonParams =  JSON.toJSONString(map);
        String sign = md5(jsonParams);
        return sign;

    }

    /**
     * MD5加密
     * @param input
     * @return
     */
    public static String md5(String input) {
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 执行加密操作
            byte[] messageDigest = md.digest(input.getBytes());
            // 将字节数组转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回加密后的字符串
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

}
